package com.client;

import java.util.ArrayList;
import java.util.Arrays;

import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.FlowPanel;

public class TagsPanel extends FlowPanel {
	private int tagAmount = 10;
	private int startIndex = 0;
	private ClickHandler clkHdlr = null;
	private int currTag = 0;
	private ArrayList<String> tags = new ArrayList<String>();

	public TagsPanel(int tagAmount, int startIndex, ClickHandler clkHdlr) {
		super();
		this.tagAmount = tagAmount;
		this.startIndex = startIndex;
		this.clkHdlr = clkHdlr;
	}

	public void addTag(String tag) {
		assert (this.currTag < this.tagAmount && 
				false == this.getWidget(this.currTag+this.startIndex).isVisible());
		TagLabel t = (TagLabel) this.getWidget(this.currTag+this.startIndex);
		t.setText(tag);
		t.setVisible(true);
		this.tags.add(tag);
		this.currTag++;
	}
	
	public void removeTag(TagLabel tag) {
		if (this.getWidgetIndex(tag)>=0) {
			tag.setVisible(false);
			this.insert(tag, this.getWidgetCount()-1);
			this.tags.remove(tag.getText());
			this.currTag--;
		}
	}
	
	public String getTagsText() {
		String text = "";
		String[] tagsText = (String[]) this.tags.toArray(new String[0]);
		Arrays.sort(tagsText);
		for (int i=0;i<this.currTag;i++) {
			if (i>0) text += " ";
			text += tagsText[i];
		}
		return text;
	}
	
	public int getTagAmount() {
		return this.currTag;
	}

	protected void onAttach() {
		for (int i = 0; i < this.tagAmount; i++) {
			TagLabel tag = new TagLabel();
			tag.addClickHandler(this.clkHdlr);
			tag.setVisible(false);
			this.add(tag);
		}
		super.onAttach();
	}

	protected void clearTags() {
		for (int i = 0; i < this.currTag; i++)
			this.getWidget(i+this.startIndex).setVisible(false);
		this.tags.clear();
		this.currTag = 0;
	}
}